<template>
  <div class="live-kit">
    <div class="join my-5">
      <el-input
        v-model="ruleForm.roomName"
        placeholder="请输入房间名"
        style="width: 200px; margin-right: 20px"
      />
      <el-input
        v-model="ruleForm.participantName"
        placeholder="请输入用户名"
        style="width: 200px"
      />
    </div>
    <el-button @click="initRoom" type="primary" :loading="isJoinLoading"
      >加入房间</el-button
    >
    <el-button @click="publish" type="primary">发布流</el-button>
    <div class="content flex items-center">
      <div class="left">
        <video id="local" />
      </div>
      <div class="right">
        <video id="remote" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { RemoteTrack, Room, RoomEvent } from "livekit-client";
import { ref } from "vue";
const ruleForm = ref({
  roomName: "room1",
  participantName: "user1"
});
const getToken = async () => {
  const res = await fetch("http://localhost:3000/getToken", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      roomName: ruleForm.value.roomName,
      participantName: ruleForm.value.participantName
    })
  });
  const data = await res.json();
  return data.data;
};
const room: Room = new Room();
const isJoinLoading = ref(false);
const initRoom = async () => {
  const wsURL = "ws://localhost:7880";
  isJoinLoading.value = true;
  const token = await getToken();
  await room.connect(wsURL, token);
  isJoinLoading.value = false;
  console.log("connected to room", room.name);
};
const publish = async () => {
  if (!room) return;
  // Turns camera track on
  const camera = await room.localParticipant.setCameraEnabled(true);
  console.log(camera);
  camera.track.attach(document.querySelector("#local"));
  // Turns microphone track on
  const voice = await room.localParticipant.setMicrophoneEnabled(true);
  voice.track.attach(document.querySelector("#local"));
};
room.on(RoomEvent.TrackSubscribed, (track: RemoteTrack) => {
  if (track.kind === "video") {
    track.attach(document.querySelector("#remote"));
  }
});
</script>

<style lang="scss" scoped>
video {
  width: 600px;
  height: 600px;
}
</style>
